<?php
namespace app\admin\controller;

use app\common\model\OrderOperate;
use app\common\model\OrderProduct;
use think\Db;
use think\Loader;
use think\Request;
use app\common\model\Product as ProductModel;
use app\common\model\Company as CompanyModel;
use app\admin\tool\Parser;
use app\common\model\Enroll as EnrollModel;
use app\common\model\Order as OrderModel;
use app\common\model\Exhibition as ExhibitionModel;
use app\common\model\Admin as AdminModel;
use app\common\model\Config as ConfigModel;
use app\common\model\Salary as SalaryModel;

/**
 * 后台管理的订单管理 有些方法是复制过来的 改造过的方法 加个标志 代表可以是用
 * Class Order
 * @package app\admin\controller
 */
class OrderAdmin extends Base{

    /**
     * 查看所有订单  修改完成 可以使用
     */
    public function index(){

        $model = OrderModel::where([])->paginate(10);

        $this->data['title'] =  '订单列表';
        $this->data['model'] = $model;
        $this->data['parser'] = new Parser();
        $this->data['column'] = $this->column();

        return view('',$this->data);
    }


    /**
     * 手动开启该订单的佣金计算
     * 该方法放在这里是用于调试佣金计算 正式的应该是后台的一个服务 方式符合计算要求的订单都会进入到队列 服务从队列中取出 计算
     */
    public function countSalary(Request $request){
        $order_id = $request->param('id');
        $order = OrderModel::get($order_id);
        if($order->is_count){
            //应该做双重检查
            $this->error("该订单已经计算过了");
        }

        $exists = SalaryModel::where('order_id',$order_id)->count();
        if($exists){
            //这就是之前订单表没有更新状态 不上去
            $order->is_count = 1;
            $order->save();
            $this->error("该订单已经计算过了");
        }

        if($order->state != 7){
            $this->error("该订单还没有完成");
        }

        //获取分成比例
        $config = ConfigModel::where('ckey','in',['rate1','rate2','rate3','rate4'])->column('ckey,cvalue','ckey');

        $data = [
            'order_id'   => $order_id,
            'company_id' => '',
            'money'      => '',
            'state'      => 0,
            'rate1'      => $config['rate1'],
            'rate2'      => $config['rate2'],
            'rate3'      => $config['rate3'],
            'rate4'      => $config['rate4'],
            'add_time'   => time(),
            'valid_time' => 0
        ];


        Db::startTrans();
        try{
            //要不要验证下每个公司的合法性 就是看看是不是B端或者对应的角色
            if(!empty($config['rate1']) && !empty($order->company_one_id)){
                //计算B端佣金
                $data['company_id'] = $order->company_one_id;
                $data['money']      = (floatval($order->total_salary) * intval($config['rate1'])) / 100;
                SalaryModel::create($data);
            }
            if(!empty($config['rate2']) && !empty($order->company_two_id)){
                //计算城市运营商佣金
                $data['company_id'] = $order->company_two_id;
                $data['money']      = (floatval($order->total_salary) * intval($config['rate2'])) / 100;
                SalaryModel::create($data);
            }
            if(!empty($config['rate3']) && !empty($order->company_three_id)){
                //计算工厂佣金
                $data['company_id'] = $order->company_three_id;
                $data['money']      = (floatval($order->total_salary) * intval($config['rate3'])) / 100;
                SalaryModel::create($data);
            }
            if(!empty($config['rate4']) && !empty($order->company_four_id)){
                //计算展览馆佣金
                $data['company_id'] = $order->company_four_id;
                $data['money']      = (floatval($order->total_salary) * intval($config['rate4'])) / 100;
                SalaryModel::create($data);
            }

            $order->is_count = 1;
            $order->save();
            Db::commit();
        }catch ( \Exception $e ){
            Db::rollback();
            $this->success("计算失败");
        }


        $this->success("计算成功");




    }


    /**
     * 订单详情
     * @param Request $request
     * @throws
     * @return mixed
     */
    public function show(Request $request){
        $id = $request->param('id');
        $model = OrderModel::get($id);
        $model->picture_list = json_decode($model->picture_list);
        $order_product = OrderProduct::where(['order_id'=>$model->id])->select();

        $this->data['model'] = $model;
        $this->data['title'] = '订单详情';
        $this->data['order_product'] = $order_product;

        //状态处理记录
        $history = OrderOperate::where(['order_id'=>$id])->order('id desc')->select();
        $op_users = [];
        foreach( $history as $key => $val ){
            array_push($op_users,$val['op_user']);
        }
        $op_users = array_unique($op_users);
        $op_users = AdminModel::where('id','in',$op_users)->column('username,nickname','id');


        $this->data['history'] = $history;
        $this->data['op_users'] = $op_users;

        return view('',$this->data);
    }

    /**
     * @param Request $request
     * @return \think\response\View
     * @throws
     */
    public function add(Request $request){
        $user_id = $request->param('user_id');
        if(!$user_id){
            $this->error("请先选择用户");
        }
        $this->data['title'] = '添加订单';
        $this->data['user_id'] =  $user_id;
        $this->data['expo'] = CompanyModel::where(['type'=>3])->select(); //展览中心不会很多

        return view("",$this->data);
    }


    /**
     * 审核过后 是不能再次编辑的 除非后面的把 审核打回原形
     * @return \think\response\View
     */
    public function edit(){

        $this->data['title'] = '订单编辑';

        return view("",$this->data);

    }

    /**
     * 添加订单
     * @param Request $request
     */
    public function handle(Request $request){
        $data = $request->post();
        $data['op_user'] = '';
        $data['user_id'] = '';
        $data['total_price'] = '';
        $data['total_salary'] = '';
        $data['company_one_id'] = '';
        $data['company_two_id'] = '';
        $data['company_three_id'] = '';
        $data['company_four_id'] = '';
        $data['picture_list'] = [];
        $data['desc'] = '';
        $data['state'] = '';
        $data['exhibition_id'] = '';
        $data['address'] = '';
        $data['zcode'] = '';
        $data['cellphone'] = '';
        $data['add_time'] = '';
        $data['update_time'] = '';

        //order order_product order_operate

        $validate = Loader::validate('Order');
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }

        $data['op_user'] = $this->admin->id;
        if(empty($data['id'])){
            $data['add_time'] = $data['update_time'] = time();
            $model = new ExhibitionModel();
            $model->data($data);
            if($model->allowField(true)->save()){
                $this->success("新增成功");
            }
        }else{
            $data['update_time'] = time();
            $model = new ExhibitionModel();
            if($model ->allowField(true)->save($data,['id'=>$data['id']])){
                $this->success("更新成功");
            }
        }

        $this->error("操作失败");
    }

    /**
     * 下订单的审核选择产品 的列表
     */
    public function productList(){

        $products = ProductModel::where([])->paginate(10);
        //查找工厂

        $factory_list = [];
        foreach($products as $key => $val ){
            array_push($factory_list,$val['factory_id']);
        }

        $list = [];
        if($factory_list){
            $list = CompanyModel::where('id','in',$factory_list)->column('company_name','id');
        }

        $this->data['title'] = '产品列表';
        $this->data['column'] = [
            'title'=>['name'=>'名称','fun'=>'text','options'=>''],
            'serial_number'=>['name'=>'产品编号','fun'=>'text','options'=>''],
            'market_price'=>['name'=>'市场价格','fun'=>'text','options'=>''],
            'sell_price'=>['name'=>'团购价格','fun'=>'text','options'=>''],
            'salary'=>['name'=>'佣金','fun'=>'text','options'=>''],
            'factory_id'=>['name'=>'所属工厂','fun'=>'translateMulti','options'=>['map'=>$list]],
            'add_time'=>['name'=>'添加时间','fun'=>'datetime','options'=>['format'=>'Y-m-d']],
        ];
        $this->data['model'] = $products;
        $this->data['parser'] = new Parser();
        return view('',$this->data);

    }

    /**
     * 本次不做购物车  缓存直接存储在页面上  一次性解决  刷新就重新选择
     * 加入到购物车
     * @param Request $request
     */
    public function addToCart(Request $request){

    }

    public function process(Request $request){
        var_dump($request->post());
    }

    /**
     * 添加订单  关联 order order_product order_
     * @param Request $request
     * @throws
     */
    public function create(Request $request){
        $post = $request->post();
        $validate = Loader::validate('Order');
        if(!$validate->check($post)){
            $this->error($validate->getError());
        }


        //判断product_list 是否有不同工厂的产品  只用到前端传来的参数 id number 其他的后台重新计算
        $product_list = [];
        $number_list = [];
        foreach($post['product_list'] as $key => $val ){
            array_push($product_list,$val['id']);
            $number_list[$val['id']] = $val['number'];
        }
        $product_list = ProductModel::where('id','in',$product_list)->column('id,factory_id,sell_price,salary,market_price','id');
        $factory_list = [];
        foreach($product_list as $key => $val ){
            array_push($factory_list,$val['factory_id']);
        }
        $factory_list = array_unique($factory_list);
        if(count($factory_list) != 1){
            $this->error("一个订单不能有两个工厂的商品");
        }

        //计算总价格 和 总佣金 构造产品数据
        $total_price = 0;
        $total_salary = 0;
        $product_data = [];
        foreach( $product_list as $key => $val ){
            $item_total_price = floatval($val['sell_price']) * $number_list[$val['id']];
            $item_total_salary = floatval($val['salary']) * $number_list[$val['id']];
            $total_price += $item_total_price;
            $total_salary += $item_total_salary;
            $product_data[$val['id']]['product_id'] = $val['id'];
            $product_data[$val['id']]['total_price'] = $item_total_price;
            $product_data[$val['id']]['total_salary'] = $item_total_salary;
            $product_data[$val['id']]['number'] = $number_list[$val['id']];
            $product_data[$val['id']]['sell_price'] = $val['sell_price'];
            $product_data[$val['id']]['salary'] = $val['salary'];
            $product_data[$val['id']]['market_price'] = $val['market_price'];
        }


        $data['op_user'] = $this->admin->id;
        $data['user_id'] = $post['user_id'];
        $data['order_num'] = $this->createOrderNum();
        $data['total_price'] = $total_price;
        $data['total_salary'] = $total_salary;
        $data['company_one_id'] = 0;  //用户选择
        $data['company_two_id'] = 0;   //根据地区
        $data['company_three_id'] = $factory_list[0];
        $data['company_four_id'] = $post['company_four_id'];  //用户选择
        $data['picture_list'] = json_encode($post['picture_list']);
        //$data['desc'] = $post['desc'];
        $data['state'] = 0;
        //展览id到底是传进来 还是 找最后一个  感觉传进来会好一点
        $data['exhibition_id'] = 0;
        $data['address'] = $post['address'];
        $data['zcode'] = $post['zcode'];
        $data['cellphone'] = $post['cellphone'];
        $now = time();
        $data['add_time'] = $now;
        $data['update_time'] = $now;

        $exhibition = ExhibitionModel::where('exhibition_time','>',time())->where('state',0)->order('exhibition_time desc')->find();
        $data['exhibition_id'] = $exhibition['id'];

        //找到B端， 城市运营商  B端是在用户 报名的时候已经选择好的   城市运营商根据地区获取    如果B端 用户没有选 要不要随机给他一个   不需要了 因为在报名的时候已经随机给了一个了 城市运营商也在开始的时候就给出
        $enroll = EnrollModel::where('user_id',$post['user_id'])->where('exhibition_id',$exhibition['id'])->order('id desc')->find();
        $data['company_one_id'] = $enroll['company_one_id'];
        $data['company_two_id'] = $enroll['company_two_id'];


        Db::startTrans();
        try{
            $order = OrderModel::create($data);

            foreach($product_data as $key => &$val){
                $val['order_id'] = $order->id;
            }
            Db::table('order_product')->insertAll($product_data);

            OrderOperate::create([
                'op_user'  => $this->admin->id,
                'order_id' => $order->id,
                'action'   => 0,
                'add_time' => time()
            ]);

            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage().':'.$e->getCode().":".$e->getLine().":".$e->getFile());
        }

        //不能在try中 使用 会跳进 catch的
        $this->success("操作成功");


    }

    /**
     * 修改订单
     * @param Request $request
     */
    public function update(Request $request){

    }

    /**
     * 获取商品的信息
     * @param Request $request
     * @throws \think\exception\DbException
     */
    public function getProduct(Request $request){
        $id = $request -> param('product_id');
        $product = ProductModel::get($id);

        $this->success('获取成功','',$product);
    }

    protected function createOrderNum(){
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000,99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for($i=0; $i<$order_id_len; $i++){
            $order_id_sum += (int)(substr($order_id_main,$i,1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_num = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
        $res = OrderModel::where('order_num',$order_num)->count();
        if($res){
            return $this->createOrderNum();
        }
        return $order_num;
    }


    /**
     *
     */
    public function column(){
        return [
            'order_num'=>['name'=>'订单编号','fun'=>'text','options'=>''],
            'total_price'=>['name'=>'总金额','fun'=>'text','options'=>''],
            'total_salary'=>['name'=>'总佣金','fun'=>'text','options'=>''],
            'cellphone' =>['name'=>'联系人手机','fun'=>'text','options'=>''],
            'add_time'=>['name'=>'添加时间','fun'=>'datetime','options'=>['format'=>'Y-m-d H:i']],
            'update_time'=>['name'=>'更新时间','fun'=>'text','options'=>[]],
        ];
    }


}